package org.cloud.gateway.filter;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpStatus;
import org.cloud.admin.auth.client.client.SysAuthClient;
import org.cloud.common.exception.SlothCloudException;
import org.cloud.common.model.R;
import org.cloud.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * 后台管理系统鉴权拦截器
 * @author wangyuan
 * @since 2019年6月4日 上午10:13:11
 *
 */
@Component
public class AdminAccessFilter extends ZuulFilter {
	
	private static final Logger logger = LoggerFactory.getLogger(AdminAccessFilter.class);
	
	private static final List<String> INCLUDE_URI_PATTERNS = new ArrayList<>();
	static {
		INCLUDE_URI_PATTERNS.add("^(/admin-auth/).*");
		INCLUDE_URI_PATTERNS.add("^(/admin/).*");
		INCLUDE_URI_PATTERNS.add("^(/scheduler/).*");
	}
	
	private static final List<String> SPECIAL_URI = new ArrayList<>();
	static {
		SPECIAL_URI.add("/admin-auth/captcha.jpg");
		SPECIAL_URI.add("/admin-auth/sys/login");
	}
	
	@Resource
	private SysAuthClient sysAuthClient;

	@Override
	public Object run() throws ZuulException {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		String servletPath = request.getServletPath();
		//获取去掉统一请求前缀的uri
		String requestUri = servletPath.substring(servletPath.indexOf("/"));
		requestUri = requestUri.substring(servletPath.indexOf("/"));
		
		//获取token
		String token = getTokenFromRequest(request);
		if(StringUtils.isBlank(token)) {
			requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
			requestContext.setThrowable(new SlothCloudException("未授权的访问"));
			return false;
		}
		R r = sysAuthClient.authenticateService(token, requestUri);
		logger.info("反馈结果：{}", r);
		if(Integer.valueOf(0).equals(r.getCode())) {
			return true;
		} else {
			requestContext.setResponseStatusCode(r.getCode());
			requestContext.setThrowable(new SlothCloudException(r.getMsg()));
			return false;
		}
	}

	@Override
	public boolean shouldFilter() {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		
		//是请求后台管理系统的路径
		//是请求需要登录之后才能访问的接口
		logger.info("ContextPath={}", request.getContextPath());
		logger.info("LocalAddr={}", request.getLocalAddr());
		logger.info("LocalName={}", request.getLocalName());
		logger.info("PathInfo={}", request.getPathInfo());
		logger.info("RemoteAddr={}", request.getRemoteAddr());
		logger.info("RemoteHost={}", request.getRemoteHost());
		logger.info("RequestURI={}", request.getRequestURI());
		logger.info("ServerName={}", request.getServerName());
		logger.info("ServletPath={}", request.getServletPath());
		logger.info("RequestURL={}", request.getRequestURL());
		
		String servletPath = request.getServletPath();
		for(String item : INCLUDE_URI_PATTERNS) {
			if(Pattern.matches(item, servletPath)) {
				//特殊的不需要过滤器处理的URL
				for(String specialUriItem : SPECIAL_URI) {
					if(specialUriItem.equals(servletPath)) {
						return false;
					}
				}
				
				logger.info("过滤器{}将应用在请求{}之上", getClass().getSimpleName(), servletPath);
				return true;
			}
		}
		
		return false;
	}

	@Override
	public int filterOrder() {
		return 1;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}
	
	/**
	 * 获取token
	 * @param request
	 * @return
	 */
	private String getTokenFromRequest(HttpServletRequest request){
        //从header中获取token
        String token = request.getHeader("Auth-Token");

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        return token;
    }

}
